package com.ericsson.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ericsson.web.core.Constants;
import com.ericsson.web.core.HSQLDatabase;
import com.ericsson.web.core.IDatabase;
import com.ericsson.web.core.Utils;

public class SearchFriends extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest request, 
			HttpServletResponse response) 
	throws ServletException, IOException {
		response.setContentType("text/html");
		
		String searchStr = request.getParameter("search");
		IDatabase db = HSQLDatabase.getInstance();
		Map<Integer, String> friends = null;
		if(Utils.isEmpty(searchStr)) {
			friends = db.getAllUsersExceptMe((Integer)(request.getSession().getAttribute(Constants.USERID)));
		} else {
			friends = db.searchFiendByUserName(searchStr);
		}
		
		PrintWriter out = response.getWriter();
		out.println("Search string: " + searchStr + "<p>");
		for(Integer i : friends.keySet()) {
			out.println("<a href=\"" + request.getContextPath() + "/friend.jsp" + "?id=" + i +"\">"
					+ friends.get(i) + "</a>");
		}
	}
	
	@Override
	protected void doPost(HttpServletRequest request, 
			HttpServletResponse response) 
	throws ServletException, IOException {
		doGet(request, response);
	}
}
